<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag, ElUpload, ElIcon, ElMessage, ElInputNumber } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getTreeDepartmentsApi,
  UpdateDepartmentApi,
  saveDepartmentApi,
  deleteDepartmentApi,
  downloadDepartmentTemplateApi,
  exportDepartmentsApi
} from '@/api/department'
import type { DepartmentItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/DepartmentWrite.vue'
import Detail from './components/DepartmentDetail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import * as XLSX from 'xlsx'
import { Plus } from '@element-plus/icons-vue'
const PATH_URL = import.meta.env.VITE_API_BASE_PATH
import { useUserStoreWithOut } from '@/store/modules/user'
import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const userStore = useUserStoreWithOut()
const uploadUrl = PATH_URL + 'api/Department/ExportDepartments'
const headers = ref({ Authorization: userStore.getToken ?? '' })
console.log('uploadUrl', uploadUrl)
let list: DepartmentItem[] = []
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    // const { currentPage, pageSize } = tableState
    const res = await getTreeDepartmentsApi({
      // pageNo: unref(currentPage),
      // pageRow: unref(pageSize),
      // pageModel: {...unref(searchParams)  }
      ...unref(searchParams)
    })
    list = res.data || []
    return {
      list: list,
      total: res.data?.length || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDepartmentApi(unref(ids))
    return !!res
  }
})
const { loading, dataList } = tableState //total, currentPage, pageSize
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'depNo',
    label: t('userDemo.depNo')
  },
  {
    field: 'depName',
    label: t('userDemo.departmentName')
  },
  {
    field: 'stationNo',
    label: t('site.stationNo'),
    search: {
      hidden: true
    }
  },
  {
    field: 'stationName',
    label: t('site.stationName'),
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'isDelete',
  //   label: t('userDemo.status'),
  //   search: {
  //     hidden: true
  //     // ,
  //     // component: 'Select',
  //     // componentProps: {
  //     //   options: [
  //     //     {
  //     //       value: 0,
  //     //       label: t('userDemo.disable')
  //     //     },
  //     //     {
  //     //       value: 1,
  //     //       label: t('userDemo.enable')
  //     //     }
  //     //   ]
  //     // }
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const status = data.row.status
  //         return (
  //           <>
  //             <ElTag type={status === 0 ? 'danger' : 'success'}>
  //               {status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //             </ElTag>
  //           </>
  //         )
  //       }
  //     }
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: [
  //         {
  //           value: 0,
  //           label: t('userDemo.disable')
  //         },
  //         {
  //           value: 1,
  //           label: t('userDemo.enable')
  //         }
  //       ]
  //     }
  //   },
  //   detail: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <>
  //             <ElTag type={data.isDelete === 0 ? 'danger' : 'success'}>
  //               {data.isDelete === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //             </ElTag>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'saveFileDay',
    label: '保存文件天数',
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.saveFileDay == 0 ? '无限制' : data.row.saveFileDay}</>
        }
      }
    },
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.saveFileDay == 0 ? '无限制' : data.saveFileDay}</>
        }
      }
    },
    form: {
      component: 'InputNumber',
      componentProps: {
        min: 0
      }
    }
  },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: t('userDemo.remark'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 5
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.remark}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: 260,
    align: 'center',
    fixed: 'right',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              {haspermiss.value.includes('编辑') ? (
                <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              {haspermiss.value.includes('删除') ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentItem | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delData = async (row: DepartmentItem | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.guid]
    : elTableExpose?.getSelectionRows().map((v: DepartmentItem) => v.guid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DepartmentItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    let res
    if (actionType.value == 'edit') {
      res = await UpdateDepartmentApi(formData).finally(() => {
        saveLoading.value = false
      })
    } else {
      res = await saveDepartmentApi(formData).finally(() => {
        saveLoading.value = false
      })
    }

    if (res) {
      dialogVisible.value = false
      // currentPage.value = 1
      getList()
    }
  }
}
const showExport = ref(false)

interface DepartmentItemCN {
  部门编号: string
  部门名称: string
  上级部门编号: string
  上级部门: string
  备注: string
  创建时间: string
  文件保存天数?: string
  采集站编号?: string
  采集站名称?: string
}
let arr: DepartmentItemCN[] = []
const handleData = () => {
  console.log('handleData-----', list)
  // let arr: DepartmentItemCN[] = []
  list.map((item) => {
    arr.push({
      部门编号: item.depNo,
      部门名称: item.depName,
      上级部门编号: '',
      上级部门: '',
      文件保存天数: '', //item.saveFileDay == 0 ? '永久' : item.saveFileDay +
      采集站编号: item.stationNo,
      采集站名称: item.stationName,
      备注: item.remark,
      创建时间: item?.createTime || ''
    })
    if (item?.children) {
      handleD(item)
    }
  })
  return arr
}

const handleD = (item) => {
  if (item?.children) {
    item.children.map((nitem) => {
      arr.push({
        部门编号: nitem.depNo,
        部门名称: nitem.depName,
        上级部门编号: item.depNo,
        上级部门: item.depName,
        文件保存天数: item.saveFileDay == 0 ? '永久' : item.saveFileDay + '',
        采集站编号: item.stationNo,
        采集站名称: item.stationName,
        备注: nitem.remark,
        创建时间: nitem?.createTime || ''
      })
      handleD(nitem)
    })
  }
}

const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '部门列表.xlsx')
}
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    hideDialog()
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const hideDialog = () => {
  showExport.value = false
}
const downExcel = async () => {
  const res = await downloadDepartmentTemplateApi()
  if (res) {
    const excelFile = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })

    // const url = URL.createObjectURL(excelFile)
    const url = window.URL.createObjectURL(excelFile)
    const a: HTMLAnchorElement = document.createElement('a')
    // 设置<a>元素的属性
    a.href = url
    a.download = '部门模板.xlsx'
    // 将<a>元素添加到文档中
    document.body.appendChild(a)
    // 触发点击事件
    a.click()
    URL.revokeObjectURL(a.href)
    // 移除<a>元素
    document.body.removeChild(a)
  }
}
</script>

<template>
  <ContentWrap>
    <!-- <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" /> -->

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData(null)"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>

      <BaseButton type="primary" @click="showExport = true" v-if="haspermiss.includes('导入')">{{
        t('exampleDemo.import')
      }}</BaseButton>
      <BaseButton type="primary" @click="exportToExcel" v-if="haspermiss.includes('导出')">{{
        t('exampleDemo.exprot')
      }}</BaseButton>
      <BaseButton type="primary" @click="downExcel">下载模板</BaseButton>
    </div>

    <Table
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="guid"
      default-expand-all
      :loading="loading"
      @register="tableRegister"
      :height="600"
      :showAction="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail
      v-if="actionType === 'detail'"
      :current-row="currentRow"
      :detail-schema="allSchemas.detailSchema"
    />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="showExport" title="导入模板">
    <div class="uploaddiv">
      <!-- :action="uploadUrl" -->
      <ElUpload
        accept=".xlsx, .xls"
        drag
        action="/api/Department/ExportDepartments"
        :headers="headers"
        :on-success="successFile"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.xlsx, .xls</div>
      </ElUpload>
    </div>
    <template #footer>
      <BaseButton @click="showExport = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
.uploaddiv {
  margin: 0 20px;
}
</style>
